#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/11/13 10:52
# @Author  : Yunhao.Cao
# @File    : queue.py
from __future__ import unicode_literals
from multiprocessing import Manager
from logger import Logger

__author__ = 'Yunhao.Cao'

__ALL__ = ["WebRequestQueue", ]


class RequestTask:
    """
    请求任务
    """
    def __init__(self, url, fail_time=0):
        self._url = url
        self._fail_time = fail_time

    @property
    def url(self):
        return self._url

    @property
    def fail_time(self):
        return self._fail_time

    @fail_time.setter
    def fail_time(self, value):
        self._fail_time = value


class WebRequestQueue(object):
    """
    请求任务队列
    """

    def __init__(self, maxsize=None):
        self._maxsize = maxsize
        # 进程管理类
        _manager = Manager()
        # 进程同步队列
        self._queue = _manager.Queue(self._maxsize)
        # 进程同步锁
        self._lock = _manager.Lock()

    def get(self):
        """
        获取下一个网络请求任务
        :return:
        """
        self._lock.acquire()
        try:
            next_ = self._queue.get()
        finally:
            self._lock.release()
        return next_

    def put(self, task):
        """
        添加一个网络请求任务
        :return:
        """
        if not isinstance(task, RequestTask):
            raise
        self._queue.put(task)


if __name__ == '__main__':
    q = WebRequestQueue()
    q.put("https://creditcard.bankcomm.com/content/pccc-biz/discount/data/27_1509439575715.show.html")
    task = q.get()
    print(task)
